package com.dartfar.workflow.helper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
import org.dom4j.xpath.DefaultXPath;

/**
 * 流程辅助
 * @author 王琦
 *
 */

public class WorkflowHelper {
	
		private Document doc;
		public WorkflowHelper() {
			super();
			// TODO Auto-generated constructor stub
		}

		public WorkflowHelper(Document doc) {
			super();
			this.doc = doc;
		}
		public WorkflowHelper(String jbdlPath){
			try {
				doc = new SAXReader().read(jbdlPath);
			} catch (DocumentException e) {
				System.out.println("流程文件解析异常!");
				e.printStackTrace();
			}
		}
		/**
		 * 获取JPDL中全部task结点列表
		 * @param jpdlPath
		 * @return
		 */
		@SuppressWarnings("rawtypes")
		public List getTaskNodes() {
			List nodes = new ArrayList();
	        XPath xpath = newXPath("//jbpm:task");
	        nodes = xpath.selectNodes(doc);
			return nodes;
		}
		/**
		 * 构建带有xmlns的xpath解析
		 * @param xpathModel
		 * @return
		 */
		public XPath newXPath(String xpathModel) {
			XPath xPath = new DefaultXPath(xpathModel);
	        Map<String, String> xmlns = new HashMap<String, String>();
	        xmlns.put("jbpm", "http://jbpm.org/4.4/jpdl");
	        xPath.setNamespaceURIs(xmlns);
	        return xPath;
		}
		/**
		 * 获取JPDL的process结点
		 * @return
		 */
		public Element getProcessNode() {
			XPath xpath = newXPath("/jbpm:process");
	        Element process = (Element)xpath.selectSingleNode(doc);
	        return process;
		}
		/**
		 * 获取JPDL的描述信息
		 */
		public String getDescript(){
			XPath xpath = newXPath("/jbpm:process/jbpm:description");
	        Element descript = (Element)xpath.selectSingleNode(doc);
	        String des=descript==null?"未定义":descript.getData().toString();
	        return des;
		}
		/**
		 * 用于获取JPDL的预定义Variable节点的元素
		 * @param varName
		 * @return
		 */
		public Element getVariableNode(String varName) {
			StringBuffer xpathModel = new StringBuffer("/jbpm:process/jbpm:variable[@name='");
			xpathModel.append(varName);
			xpathModel.append("']/jbpm:string");
			XPath xpath = newXPath(xpathModel.toString());
	        Element varNode = (Element) xpath.selectSingleNode(doc);
			return varNode;
		}
}
